package com.primestone.cim.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

import com.primestone.cim.util.enums.AlgorithmEnum;
import com.primestone.cim.util.enums.EncodingEnum;

/**
 * @author cesar.mateus
 * May 7, 2013 6:34:45 PM
 * HashingUtil.java
 * CIMUtil
 * 
 */
public class HashingUtil {

	private static MessageDigest SHA512_DIGEST;
	private static MessageDigest SHA256_DIGEST;
	static {
		try {
			SHA512_DIGEST = MessageDigest.getInstance(AlgorithmEnum.SHA512.getName());
			SHA256_DIGEST = MessageDigest.getInstance(AlgorithmEnum.SHA256.getName());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @param base
	 * @param algorithm 
	 * @param encoding 
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws UnsupportedEncodingException 
	 */
	public static String getHash(String base, AlgorithmEnum algorithm, EncodingEnum encoding) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest digest = MessageDigest.getInstance(algorithm.getName());
		byte[] hash = digest.digest(new StringBuilder(base).append(StringUtil.WORD).toString().getBytes(encoding.getName()));
		return Hex.encodeHexString(hash);	        
	}
	
	/**
	 * @param base
	 * @param encoding
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String getSHA512(String base, EncodingEnum encoding) throws UnsupportedEncodingException {
		byte[] hash = SHA512_DIGEST.digest(new StringBuilder(base).append(StringUtil.WORD).toString().getBytes(encoding.getName()));
		return Hex.encodeHexString(hash);	        
	}
	
	/**
	 * @param base
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getSHA512AndUTF8(String base) throws UnsupportedEncodingException {
		byte[] hash = SHA512_DIGEST.digest(new StringBuilder(base).append(StringUtil.WORD).toString().getBytes(EncodingEnum.UTF8.getName()));
		return Hex.encodeHexString(hash);	        
	}
	
	/**
	 * @param base
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getSHA256AndUTF8(String base) throws UnsupportedEncodingException {
		byte[] hash = SHA256_DIGEST.digest(new StringBuilder(base).append(StringUtil.WORD).toString().getBytes(EncodingEnum.UTF8.getName()));
		return Hex.encodeHexString(hash);	        
	}
}